<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@include file="head.jsp"%>
<%
	String id = request.getParameter("id");
	id = id == null ? "create" : id;
	String tableName = request.getParameter("tableName");
	tableName = tableName == null ? "" : tableName;
	String projectId = request.getParameter("projectId");
	projectId = projectId == null ? "" : projectId;
%>

<div class="am-cf admin-main">
	<!-- content start -->
	<div class="admin-content">
		<div class="admin-content-body">
			<div class="am-cf am-padding am-padding-bottom-0">
				<div class="am-fl am-cf">
					<strong class="am-text-primary am-text-lg">构建项目</strong> / <small>html相关选项</small>
				</div>
			</div>
			<hr>
			<input type="hidden" id='id_id' value="<%=id%>" /> <input type="hidden" id='id_tableName' value="<%=tableName%>" />
			<input type="hidden" id='projectId' value="<%=projectId%>" />

			<div class="am-g">
				<div class="am-u-sm-12">
					<form class="am-form">
						<div class="am-form-group am-fr">
					    	<button type="button" class="am-btn am-btn-danger" data-am-modal="{target: '#my-popup'}"> 关联</button>
							<button type="button" id="id_project_save" class="am-btn am-btn-primary">保存修改</button>
							<button type="button" id="id_project_next" class="am-btn am-btn-primary">完成</button>
						</div>

						<table class="am-table am-table-striped am-table-hover table-main">
							<thead>
								<tr>
									<th class="table-id">字段/显示名</th>
									<th class="table-type" >是否主键/关联</th>	
									<th class="table-type" >字段描述/搜索类型</th>
									<th class="table-title">修改类型/字段类型</th>
									<th class="table-title">使用类型</th>
									<th class="table-title">下拉框选项/显示排序</th>
									<th class="table-title">验证规则/验证说明</th>
									<!-- <th class="table-title">显示宽度</th> -->
									<!-- <th class="table-author am-hide-sm-only">操作</th> -->
								</tr>
							</thead>
							<tbody id="id_tb_body">
							</tbody>
						</table>
						<hr>
						<p>说明：请确保该系统所在机器能访问你的数据库</p>
					</form>
				</div>
			</div>
		</div>
	</div>
</div>

<div class="am-popup" id="my-popup">
  <div class="am-popup-inner">
    <div class="am-popup-hd">
      <h4 class="am-popup-title">关联</h4>
      <span data-am-modal-close  class="am-close">&times;</span>
    </div>
    <div class="am-popup-bd">
关联字段: <select id="associationField">
 
     </select><br/><br/>
     
选择库:	 <select id="selectionLibrary">
     </select><br/><br/>   
     
选择表: <select id="selectionTable">

      </select><br/><br/> 
 选择字段: <select id="selectionField">
 
       </select><br/><br/>   
 关联名称:<select id="associationName">
 
       </select>
   
     </div>
     <button id="addToData"  onclick="hiddenData();">添加</button>
   </div> 
 </div>
 
<script type="text/javascript">
$().ready(function(){
	associationField();
	selectionLibrary();
});

   
function associationField(){     
	$.ajax({
	        url:'mvc/html/associationField.do',
		type : "POST",
		data : {	
			"id":$("#id_id").val(),
			"tableName":$("#id_tableName").val()
		},
		success : searchCallBack,
		error : function() {
			showMsg("请求异常,请稍等!");
		}
	});
	function searchCallBack(dataObj) {				
			if (dataObj && dataObj.success) {
				var list='<option value="">请选择</option>';
				for(var i = 0; i < dataObj.data.length; i++){		
					list+='<option value='+dataObj.data[i].columnName+'>'+dataObj.data[i].columnName+'</option>';
				}
				$("#associationField").html(list);
			
			} else {
				alert(data.message);
			}
		
		}
}

function selectionLibrary(){     
	$.ajax({
	        url:'mvc/html/selectionLibrary.do',
		type : "POST",
		data : {	
			"projectId":$("#projectId").val()
		},
		success : searchCallBack,
		error : function() {
			showMsg("请求异常,请稍等!");
		}
	});
	function searchCallBack(dataObj) {			
			if (dataObj && dataObj.success) {
				var list='<option value="">请选择</option>';
				for(var i = 0; i < dataObj.data.length; i++){						
					list+='<option value='+dataObj.data[i].jdbcUrl+'>'+dataObj.data[i].bizName+'</option>';
				}
				$("#selectionLibrary").html(list);
			} else {
				alert(data.message);
			}
		
		}
}
 

 $("#selectionLibrary").change(function(){ 
	 if($("#selectionLibrary").val()==""){
		 return;
	 }
	    $.ajax({
	        url:'mvc/html/selectionTable.do',
		type : "POST",
		data : {		
			"selectionLibrary":$("#selectionLibrary").val()
		},
		success : searchCallBack,
		error : function() {
			showMsg("请求异常,请稍等!");
		}
	});
	function searchCallBack(dataObj) {				
			if (dataObj && dataObj.success) {
				$("#selectionTable").html("");
				var list='<option value="">请选择</option>';
				for(var i = 0; i < dataObj.data.length; i++){	
			
					list+='<option value='+dataObj.data[i].tableName+'>'+dataObj.data[i].tableName+'</option>';
				}
				$("#selectionTable").html(list);
			} else {
				alert(data.message);
			}	
		}
	});




 $("#selectionTable").change(function(){
	 if($("#selectionTable").val()==""){
		 return;
	 }
	    $.ajax({
	        url:'mvc/html/selectionField.do',
		type : "POST",
		data : {		
			"selectionTable":$("#selectionTable").val()
		},
		success : searchCallBack,
		error : function() {
			showMsg("请求异常,请稍等!");
		}
	});
	function searchCallBack(dataObj) {				
			if (dataObj && dataObj.success) {
				$("#selectionField").html("");
				$("#associationName").html("");
				var list='<option value="">请选择</option>';
				for(var i = 0; i < dataObj.data.length; i++){		
					list+='<option value='+dataObj.data[i].columnName+'>'+dataObj.data[i].columnName+'</option>';
				}
				$("#selectionField").html(list);
				$("#associationName").html(list);
			} else {
				alert(data.message);
			}	
		}
	});



 function hiddenData(){
		var tdStr = "<tr><td>" + $("#selectionField").val() + 
		    "<input name='titleName' value='" + $("#associationName").val() + "' />" +
			"<input type='hidden'  name='columnName' value='" + $("#selectionField").val() + "' />" +
			//选择库
			"<input type='hidden'  name='selectionLibrary' value='" + $("#selectionLibrary").val() + "' />" +
			//选择表
			"<input type='hidden'  name='selectionTable' value='" + $("#selectionTable").val() + "' />" +
			//关联字段
			"<input type='hidden'  name='associationField' value='" + $("#associationField").val() + "' />" +
			//关联名称
			"<input type='hidden'  name='associationName' value='" + $("#associationName").val() + "' />" +
			"</td></tr>";
		var tdObj = $("#id_tb_body tr").last().find('td'), tdObj = tdObj.slice(1,tdObj.length).clone();
		$("#id_tb_body").append(tdStr);
		$.each( tdObj, function(i, n){
			$("#id_tb_body tr").last().append(n);
		});
		$("#id_tb_body tr").last().find('input[name=selectOperation]').val('');
		$("#id_tb_body tr").last().find('input[name=displayOrder]').val('');
		$("#id_tb_body tr").last().find('input[name=rules]').val('');
		$("#id_tb_body tr").last().find('input[name=messages]').val('');
		
		
 }
 

	var metadata = [ 'columnName', 'titleName', 'isPrimary', 'isSearch',
			'isUpdate', 'searchType', 'selectOperation', 'fieldType',
			'fieldWidth', 'displayOrder' ];

	$(function() {
		loadData();
		
		$("#id_project_save").on("click",save);
		$("#id_project_next").on("click",function () {
			window.location.href = 'tablesselect.jsp?id=' + $("#id_id").val();
		});

		
		
	});

	var a = window.location.href;
	a = a.substring(a.indexOf('?'));
	function loadData() {
		$.get("mvc/html/list" + a, function(data) {
			filltr(data.data);
		});
	}

	function getStr(s) {

		return s || '';
	}

	function save() {
		var arr = [];
		$("tbody tr").each(
				function() {
					var a = $(this).find("input");
					var b = $(this).find("select");
					var obj = {};
					$(a).each(
							function() {
								var name = $(this).attr("name");
								var value = '';
								
								if ($(this).prop("type") == 'radio'
										|| $(this).prop("type") == 'checkbox') {
									
									value =  $(this).prop("checked")  ? 'true' : 'false';
								} else {
									value = $(this).val();
								}
								if((name == 'rules' || name == 'messages') && value != ''){
									console.log(name);
									console.log(value);
									obj[name] = JSON.parse(value);
								}else{
									obj[name] = value;
								}
								console.log(obj);
							});
					$(b).each(
							function() {
								var name = $(this).attr("name");
								var value = $(this).val();
					
								obj[name] = value;
							});
					
					arr.push(obj)
				});
		console.log(arr);

		$.post("mvc/html/add", {
			'bizId' : $('#id_id').val(),
			'tableName' : $('#id_tableName').val(),
			'data' : JSON.stringify(arr)
		}, function(data) {
			alert(data);
		});

		return arr;

	}

	function ccc(t, n, prj) {
		var html = "<input type='" +  t +  "' name='" + n + "' value='true' ";
		if ( prj[n] == 'true') {
			html += " checked";
		}
		html += ' />';
		return html;
	}
	
	function filltr(data) {
		data = data || [];
		$("#id_tb_body").html("");
		for ( var idx in data) {
			var context = "",selectOperation = "";
			var prj = data[idx];
			var columnName=data[idx].columnName;
			var title = prj.titleName.replace(/：/g,":");
			title = title.replace(/，/g,",");
			title = title.replace(/；/g,";");
			title = title.replace(/\s/g,"");
			var outLike="";
			var textarea="";
			var status="";
			var date_time="";
			var isPrimary = getStr(prj.isPrimary);
			if(data[idx].searchType==""&&columnName.indexOf("name")>-1||data[idx].searchType==""&&columnName.indexOf("title")>-1){
				outLike= "<option value='la' selected>后模糊查</option>"
			}else{
				outLike= "<option value='la' " + ( getStr(prj.searchType) == 'la' ? 'selected' : '' ) + ">后模糊查</option>"			
			}
			if(data[idx].fieldType==""&&columnName.indexOf("desc")>-1||data[idx].fieldType==""&&columnName.indexOf("content")>-1){
				textarea= "<option value='textarea' selected>textarea</option>"
			}else{
				textarea= "<option value='textarea' " + ( getStr(prj.fieldType) == 'textarea' ? 'selected' : '' ) + ">textarea</option>"			
			}
			if(data[idx].fieldType==""&&columnName.indexOf("status")>-1||data[idx].fieldType==""&&columnName.indexOf("type")>-1){
				status= "<option value='select' selected>select</option>"
			}else{
				status= "<option value='select' " + ( getStr(prj.fieldType) == 'select' ? 'selected' : '' ) + ">select</option>"
			}
			if(data[idx].fieldType==""&&columnName.indexOf("date")>-1||data[idx].fieldType==""&&columnName.indexOf("time")>-1){
				date_time= "<option value='datetime' selected>datetime</option>"
			}else{
				date_time= "<option value='datetime' " + ( getStr(prj.fieldType) == 'datetime' ? 'selected' : '' ) + ">datetime</option>"
			}
			
			
			var modify = "", modifyValue = getStr(prj.isUpdate) || '';
			var modifyArray = ["create_time","update_time","last_update_user","last_update_date","add_user","add_time","add_date","add_datetime",
				   "create_user","create_date","update_date","update_datetime","last_update_time","last_update_datetime","crumb",
				   "seller_path","seller_level"];
			var modifySelected = { "selected1":"", "selected2":"", "selected3":"", "selected4":"", "selected5":"", "selected6":"" };
			if( !modifyValue && isPrimary=="true"){
				modifySelected['selected3'] = ' selected';
			}else if( modifyValue != '' ){
				modifySelected['selected' + modifyValue] = ' selected';
			}else if( !modifyValue && (columnName == 'status' || columnName == 'sort') ){
				modifySelected['selected2'] = ' selected';
			}else if( !modifyValue && ($.inArray(columnName, modifyArray) != -1)){
				modifySelected['selected6'] = ' selected';
			}
			   
			modify = "<option value='1' " + modifySelected['selected1'] + ">皆可增改</option>" +
				     "<option value='2' " + modifySelected['selected2'] + ">不可增改</option>" +
					 "<option value='3' " + modifySelected['selected3'] + ">隐藏增改</option>" + 
					 "<option value='4' " + modifySelected['selected4'] + ">只增不改</option>" +
					 "<option value='5' " + modifySelected['selected5'] + ">只增隐改</option>" + 
					 "<option value='6' " + modifySelected['selected6'] + ">系统赋值</option>";
			
			var listdisplaySelected = "";
			var exportdisplaySelected = "";
			var listdisplay="";
			var exportdisplay="";
			var useType = getStr(prj.useType);
			if( (useType == null || useType == "[]") && isPrimary=="true" ){
				listdisplaySelected = ' selected';
				exportdisplaySelected = ' selected';
			}else if( !useType &&  (columnName.indexOf("status") != -1 || columnName.indexOf("sort") != -1) ){
				listdisplaySelected = ' selected';
			}
			if(useType.indexOf('listdisplay') != -1){
				listdisplaySelected = ' selected';
			}
			if(useType.indexOf('exportdisplay') != -1){
				exportdisplaySelected = ' selected';
			}
			listdisplay="<option value='listdisplay'  " + listdisplaySelected + ">列表显示</option>" 
			exportdisplay="<option value='exportdisplay'  " + exportdisplaySelected + ">导出显示</option>"
			
			var parentSelected = "";
			var statusSelected = "";
			var sortSelected = "";
			var fieldDes = getStr(prj.fieldDes);
			if(columnName == "parent_id" || fieldDes == "parent"){
				parentSelected = ' selected';
			}else if(columnName == "status" || fieldDes == "status"){
				statusSelected = ' selected';
			}else if(columnName == "sort" || fieldDes == "sort"){
				sortSelected = ' selected';
			}
			
			if( title.indexOf(":") != -1 ){
				selectOperation = title.substring(title.indexOf(":")+1);
				selectOperation = selectOperation.replace(/为/g,":");
				selectOperation = selectOperation.replace(/,/g,";");
				title = title.substring(0,title.indexOf(":"));
			} else if( title.indexOf(",") != -1 ) {
				title = title.substring(0,title.indexOf(","));
			}
			selectOperation = getStr(prj.selectOperation) || selectOperation;

			context += "<td>"
					+ prj.columnName
					//选择库
					+"<input type='hidden'  name='selectionLibrary' value='" + prj.selectionLibrary + "' />"
					//选择表
					+"<input type='hidden'  name='selectionTable' value='" + prj.selectionTable + "' />"
					//关联字段
					+"<input type='hidden'  name='associationField' value='" + prj.associationField + "' />"
					//关联名称
					+"<input type='hidden'  name='associationName' value='" + prj.associationName + "' />"
					+ "<input type='hidden'  name='columnName' value='" + prj.columnName + "' />"
					+ "<input name='titleName' value='" + getStr(title) + "' />";
					+ "</td>";
			context += "<td>"
					+ ccc('checkbox', 'isPrimary', prj)
					+ ccc('checkbox', 'isRelated', prj)
					+ "</td>";
			context += "<td>"
			    +"<select name='fieldDes' data-am-selected>"
				+ "<option value='not'" + (fieldDes == 'not' ? 'selected' : '' ) + ">无描述</option>"
			    + "<option value='parent' " + parentSelected + ">父级</option>"
			    + "<option value='status' " + statusSelected + ">状态</option>"
			    + "<option value='sort' " + sortSelected + ">排序</option>"
			    + "<option value='createTime' " + (fieldDes == 'createTime' ? 'selected' : '' ) + ">添加时间</option>"
			    + "<option value='updateTime' " + (fieldDes == 'updateTime' ? 'selected' : '' ) + ">修改时间</option>"
			    + "<option value='createUser' " + (fieldDes == 'createUser' ? 'selected' : '' ) + ">创建人</option>"
			    + "<option value='updateUser' " + (fieldDes == 'updateUser' ? 'selected' : '' ) + ">修改人</option>"
			    + "</select>"
			    +"<select name='searchType' data-am-selected>"
				+ "<option value='not'" + ( getStr(prj.searchType) == 'not' ? 'selected' : '' ) + ">不搜索</option>"
			    + "<option value='eq' " + ( getStr(prj.searchType) == 'eq' ? 'selected' : '' ) + ">等于查询</option>"
			    + "<option value='ne' " + ( getStr(prj.searchType) == 'ne' ? 'selected' : '' ) + ">不等于查</option>"
			    + "<option value='gt' " + ( getStr(prj.searchType) == 'gt' ? 'selected' : '' ) + ">大于查询</option>"
			    + "<option value='ge' " + ( getStr(prj.searchType) == 'ge' ? 'selected' : '' ) + ">大于等于</option>"
			    + "<option value='lt' " + ( getStr(prj.searchType) == 'lt' ? 'selected' : '' ) + ">小于查询</option>"
			    + "<option value='le' " + ( getStr(prj.searchType) == 'le' ? 'selected' : '' ) + ">小于等于</option>"
			    + outLike
			    + "<option value='like' " + ( getStr(prj.searchType) == 'like' ? 'selected' : '' ) + ">全模糊查</option>"
			    + "<option value='between' " + ( getStr(prj.searchType) == 'between' ? 'selected' : '' ) + ">区间查询</option>"
			    + "</select>"
			    +"</td>";
			context += "<td>"
			    + "<select name='isUpdate' data-am-selected>"
			    + modify
			    + "</select>"
			    +"<select name='fieldType' data-am-selected>"
				    + "<option value='text' " + ( getStr(prj.fieldType) == 'text' ? 'selected' : '' ) + ">text</option>"
				    + status
				    + "<option value='multiple select' " + ( getStr(prj.fieldType) == 'multiple select' ? 'selected' : '' ) + ">multiple select</option>"
				    + "<option value='checkbox' " + ( getStr(prj.fieldType) == 'checkbox' ? 'selected' : '' ) + ">checkbox</option>"
				    + textarea
				    + "<option value='password' " + ( getStr(prj.fieldType) == 'password' ? 'selected' : '' ) + ">password</option>"
				    + "<option value='image' " + ( getStr(prj.fieldType) == 'image' ? 'selected' : '' ) + ">image</option>"
				    + "<option value='file' " + ( getStr(prj.fieldType) == 'file' ? 'selected' : '' ) + ">file</option>"
				    + date_time
				+ "</select>"
			    + "</td>";
		  context+="<td><select name='useType'  id='useType'   data-am-selected  multiple>"
					+listdisplay
					+exportdisplay
		    		+ "<option value='importupdate'  " + (getStr(prj.useType).indexOf('importupdate')>-1 ? 'selected' : '' ) + ">导入更新</option>"
					+"</select></td>";
			// 显示名: 1为...,2为...
			context += "<td>"
			        +"<input name='selectOperation' value='" + getStr(selectOperation) + "' />"
			        +"<input name='displayOrder' value='" + getStr(prj.displayOrder) + "' />"
			        +"</td>";
			context += "<td>"
			        +"<input name='rules' value='" + getStr(prj.rules) + "' />"
			        +"<input name='messages' value='" + getStr(prj.messages) + "' />"
			        +"</td>";
			/*context += "<td><input name='fieldWidth' value='"
					+ getStr(prj.fieldWidth) + "' /></td>";*/
			/* context += "<td>"
					+ '<a class="am-btn am-btn-default am-btn-xs am-hide-sm-only" href="project.jsp?id='
					+ prj['id']
					+ '"><span class="am-icon-pencil-square-o"></span>编辑</a> '
					+ '<a class="am-btn am-btn-default am-btn-xs am-hide-sm-only"  href="javascript:deleteprj('
					+ prj['id']
					+ ')"><span class="am-icon-trash-o"></span>删除</a>'
					+ "</td>"; */

			context += "<td></td>";
			context = "<tr>" + context + "</tr>";

			$("#id_tb_body").append(context);
			$('select').selected('destroy');
			$('select').selected();
		}
	}

	function deleteprj(id) {
		$.get("mvc/project/delete?id=" + id, function(msg) {
			alert(msg);
			loadData();
		});
	}
</script>

<%@include file="bottom.jsp"%>